#!coding:utf-8
import binascii
from myPyDes import MyDes

def genMac():
    data='0200302004C030C0981100000000000001320000000302100006366222601310010029726D49121201067026870076996222601310010029726D1561560500050008168013000000010000000000DDD0702687106036303130313030383837343131303134353131323438303135365FBC996B84F4CF5D2000000000000000000822000003'
    mac_key='6ED5EA4ADD2BE4DB'
    master_key='1111111111111111'
    #DO XOR
    des=MyDes()
#    mac_key = des.des(mac_key, master_key, 1)#解密mac key
    mac_key = des.des(mac_key, master_key, 1)#解密mac key
    
    result=''
    tempRes=data[:16]
    m0_bit=get_hex_bit(tempRes)
    data=data[16:]
    while len(data)>0:
        if(len(data)<16):
            mab=data[:16]+'0'*(16-len(data))
        else:
            mab=data[:16]
        m1_bit=get_hex_bit(mab)
        data=data[16:]
        m0_bit=list(map(lambda x,y:x^y, m0_bit, m1_bit))

    tempXor = binary2Hex(m0_bit)
    temp2 = binascii.b2a_hex(tempXor)
    temp21=temp2[:16]
    temp22=temp2[16:]
    #用mac对temp21加密
    des = MyDes()
    decryptRes = des.des(temp21, mac_key, 0) #E94CBF2769A0131B
    #加密后结果与temp22异或
    decryptRes_bit = get_hex_bit(decryptRes)
    temp22_bit = get_hex_bit(temp22)
    xor_bit=list(map(lambda x,y:x^y, decryptRes_bit, temp22_bit))
    xor_bit_hex=binary2Hex(xor_bit)
    #异或后的结果再进行des加密
    cryptRes = des.des(xor_bit_hex, mac_key, 0)
    
    cryptRes_hex = binascii.b2a_hex(cryptRes)

def get_hex_bit(data):
    data = [int(c,16) for c in data] #转换成十进制数
    l = len(data) * 4
    result = [0] * l
    pos = 0
    for ch in data:
        i = 3
        while i >= 0:
            if ch & (1 << i) != 0:
                result[pos] = 1
            else:
                result[pos] = 0
            pos += 1
            i -= 1
    
    return result

def binary2Hex(source):
    '''将二进制字符数组转换成16进制字符串'''
    result = ''
#    if data_len>4:
#        return None
    while len(source)>1:
        data=source[:4]
        source=source[4:]
        ord_value = 0
        for i in range(4):
            if data[i] == 0:
                ord_value += 0
            else:
                ord_value += (data[i]*2)**(4-i-1)
        result += hex(ord_value)[2:]

    return result.upper()

def chk_des():
    mac_key = '145faa6910610d80'
    master_key = '1111111111111111'
    key2='0000000000000000'
    
    des=MyDes()
    t1 = des.des(mac_key, master_key, 1)
    t2 = des.des(key2,t1, 0)
    
genMac()    
